package com.smart.speaker.config;

import com.alibaba.dashscope.audio.asr.recognition.Recognition;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ParaFormerConfig {

    @Value("${ali.dashscope.recognizer.pool}")
    private int poolSize;

    @Bean(name = "recognitionGenericObjectPool")
    public GenericObjectPool<Recognition> recognitionGenericObjectPool() {
        RecognitionObjectFactory recognitionObjectFactory = new RecognitionObjectFactory();
        GenericObjectPoolConfig<Recognition> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(poolSize);
        config.setMaxIdle(poolSize);
        config.setMinIdle(poolSize);
        return new GenericObjectPool<>(recognitionObjectFactory, config);
    }

    public static class RecognitionObjectFactory extends BasePooledObjectFactory<Recognition> {
        public RecognitionObjectFactory() {
            super();
        }

        @Override
        public Recognition create() {
            return new Recognition();
        }

        @Override
        public PooledObject<Recognition> wrap(Recognition obj) {
            return new DefaultPooledObject<>(obj);
        }
    }
}
